import json
from http.client import responses

from django.contrib.auth import get_user_model, login, logout
from django.db import DatabaseError
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import View

User = get_user_model()

class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        # 获取表单数据，传统表单提交
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        try:
            user=User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})

        # 登录用户，状态保持
        login(request, user)

        response = redirect(reverse('index:index'))

        # 设置cookie
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        return response

class LogoutView(View):
    """用户退出登录"""

    def get(self, request):
        # 清除状态保持信息
        logout(request)
        # 响应结果 重定向到首页
        response = redirect(reverse('index:index'))
        # 删除cookie中的用户名
        response.delete_cookie('username')
        return response



class UsernameCountView(View):
    """判断用户名是否重复注册"""
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'count': count})

class MobileCountView(View):
    """判断手机号是否重复注册"""
    def get(self, request, mobile):
        print(mobile)
        count = User.objects.filter(mobile=mobile).count()
        count = User.objects.filter(username=mobile).count()
        return JsonResponse({'count': count})